package com.link.base.base.cfgproperty.controller;


import com.link.base.base.cfgproperty.encryptor.Encryptor;
import com.link.base.base.cfgproperty.model.CfgProperty;
import com.link.base.base.cfgproperty.service.CfgPropertyService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.AppConstants;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Title</p>
 * <p>系统运行参数配置</p>
 * <p>Company</p>
 *
 * @author 姚润发
 * @date 2016年9月7日  下午5:19:42
 */

@Controller
@RequestMapping("/link/cfgProperty")
public class CfgPropertyController extends BasicController<CfgProperty> {
    private static final Logger logger = LogManager.getLogger(CfgPropertyController.class);
    @Resource
    private CfgPropertyService cfgPropertyService;

    @Override
    public BasicService<CfgProperty> getBasicService() throws Exception {
        if (cfgPropertyService != null) {
            return cfgPropertyService;
        }
        throw new ServiceException("PUBLIC-005");
    }

    /**
     * (重新)加载系统参数到指定位置（缓存），系统参数有变时需要调用进行刷新
     * @author 姚润发
     * @date 2016/9
     * @param entity
     * @param qps
     * @return
     */
    @RequestMapping("/loadCfg")
    @ResponseBody
    public Map<String, Object> loadCfg(@JsonParam  CfgProperty entity,@JsonParam QueryParams qps) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            CoreUser user = UserUtil.getUser();
            if (!AppConstants.ADMIN_CORP_ID.equals(user.getCorpid())) {
                //非管理员账套则只能对自己账套的参数做刷新操作，管理员账套可以对单个或所有账套参数做刷新操作
                entity.setCorpid(user.getCorpid());
            }
            cfgPropertyService.loadCfg(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询所有记录前 或 根据条件查询记录前 做操作
     */
    @Override
    public void beforQueryAllOrExample(CfgProperty entity, HttpServletRequest request) throws Exception {
        CoreUser user = UserUtil.getUser();
        if (null == entity.getCorpid()) {
            //未设置corpid，则只查询当前账套数据，防止查询不属于自己账套数据
            entity.setCorpid(user.getCorpid());
        } else if (!user.getCorpid().equals(entity.getCorpid())) {

            if (AppConstants.ADMIN_CORP_ID.equals(user.getCorpid())) {
                //如果当前登录用户为管理账套用户则可以查询其他账套数据，企业管理下的企业参数使用
            } else {
                //corpid 与当前用户账套不同并且当前用户非管理员账套用户，防止查询管理员账套私有参数
                //只能为000或者自身
                entity.setCorpid(AppConstants.ADMIN_CORP_ID);
                //只查询公共参数
                entity.setType("Y");
            }
        }
    }

    @Override
    public void beforUpsert(CfgProperty entity, HttpServletRequest request) {
        CoreUser user = UserUtil.getUser();
        if (!AppConstants.ADMIN_CORP_ID.equals(user.getCorpid()) || StringUtils.isBlank(entity.getType())) {
            entity.setType("N");
        }
    }

    /**
     * 参数配置列表 参数值加密后 展示
     * @author yipeng.zhu@hand-china.com
     * @param entity
     * @return
     * @throws
     * @date 2018/12/5 14:35
     * @version 1.0
     */
    @RequestMapping("/queryByExamplePage")
    @ResponseBody
    @Override
    public Map<String, Object> queryByExamplePage(@JsonParam QueryParams qps, @JsonParam CfgProperty entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap(16);

        try {
            qps.preDealSecurity(request);
            CfgProperty temp = (CfgProperty) BasicModel.transformClass(entity, qps);
            this.beforQueryAllOrExample(temp, request);
            this.beforQueryExample(temp, request);
            List<CfgProperty> list = this.getBasicService().queryByExamplePage(temp);
            encryptList(list);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(temp, list.size()));
        } catch (Exception var10) {
            logger.error("CfgPropertyController捕获异常: ", var10);
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", var10.getMessage());
        }

        return result;
    }

    /**
     * 参数值  加密
     * @author yipeng.zhu@hand-china.com
     * @param list
     * @return
     * @throws
     * @date 2018/12/5 14:33
     * @version 1.0
     */
    public void encryptList(List<CfgProperty> list) {
        //是否加密显示
        String isEncrypt = "Y";
        for (CfgProperty bean : list) {
            if (isEncrypt.equals(bean.getIsEncrypt())) {
                bean.setValue(Encryptor.encrypt(bean.getValue()));
            }
        }
    }

    /**
     * 是否 加密参数配置值
     * @author yipeng.zhu@hand-china.com
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/queryById")
    @ResponseBody
    @Override
    public Map<String, Object> queryById(@JsonParam CfgProperty entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap(16);

        try {
            //是否加密显示
            String isEncrypt = "Y";
            CfgProperty record = this.getBasicService().queryById(entity);
            List<CfgProperty> list = new ArrayList();
            list.add(record);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            if (isEncrypt.equals(record.getIsEncrypt())) {
                record.setValue(Encryptor.encrypt(record.getValue()));
            }
            result.put("result", record);
            result.put("success", true);
        } catch (Exception var9) {
            logger.error("CfgPropertyController捕获异常: ", var9);
            result.put("success", false);
            result.put("result", var9.getMessage());
        }
        return result;
    }

    /**
     * 设置参数值加密展示
     * @author yipeng.zhu@hand-china.com
     * @param entity
     * @return
     */
    @RequestMapping("/encryValue")
    @ResponseBody
    public Map<String, Object> encryValue(@JsonParam CfgProperty entity) {
        HashMap result = new HashMap(16);
        try {
            //是否加密显示
            String isEncrypt = "Y";
            CfgProperty record = this.getBasicService().queryById(entity);
            if (isEncrypt.equals(record.getIsEncrypt())) {
                record.setIsEncrypt("N");
            } else {
                record.setIsEncrypt("Y");
                record.setValue(Encryptor.encrypt(record.getValue()));
            }
            this.getBasicService().update(record);
            result.put("result", record);
            result.put("success", true);
        } catch (Exception var9) {
            logger.error("CfgPropertyController捕获异常: ", var9);
            result.put("success", false);
            result.put("result", var9.getMessage());
        }
        return result;
    }

    /**
     * 未登录状态下，传入公共参数key值，查询对应的value
     *
     * @author 曲元涛
     * @date 2020/2/7 14:11
     * @param cfgProperty  企业参数对象
     */
    @RequestMapping(value = "/queryCommonPropertiesNoneLogin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryCommonPropertiesNoneLogin(@JsonParam CfgProperty cfgProperty) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            String commonKey = Optional.ofNullable(cfgProperty.getKey()).orElseThrow(() -> new BasicControllerException("请传入 key 值"));
            String commonValue = RedisUtil.getCommonProperty(commonKey);
            if (StringUtils.isBlank(commonValue)) {
                LCLogger.info().withMessageKey("queryCommonPropertiesNoneLogin:")
                        .withMessage(commonKey + "对应的value值为空，请检查企业参数配置").flush();
                throw new BasicControllerException(commonKey + "对应的value值为空，请检查企业参数配置");
            }
            result.put("result", commonValue);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}
